const postsModel = require('../model/adminPostsModel');
const categoriesModel = require('../model/admin_categoriesModel');
const moment = require('moment');
const formidable = require('formidable');
module.exports = {
  getPostsPage(req,res){
    let {pageIndex,pageSize} = req.body;
    postsModel.getPostsPage(pageIndex,pageSize,(err,result)=>{
      if(err) console.error(err);
      let resObj = {};
      if(result.length>0){
        resObj.code = 200;
        resObj.msg = '获取成功';
        result.forEach(e => {
      e.created = moment(e.create).format('YYYY-MM-DD HH:mm:ss');
    });
        resObj.data = result;
        // 获取最大页码数
        postsModel.getPostsCount((err,result)=>{
          if(err) console.error(err);
          if(result){
            let total = result[0].total;
            maxPage = Math.ceil(total/pageSize);
            resObj.maxPage = maxPage;
          };
          res.send(resObj);
        });
      }else{
        resObj.code = 401;
        resObj.msg = '获取失败';
        res.send(resObj);
      };
     
    });
  },
  delpostsById(req,res){
    postsModel.delpostsById(req.query.id,(err,result)=>{
      if(err) console.error(err);
      let resObj = {};
      if(result.affectedRows == 1){
         resObj.code = 200;
         resObj.msg = '删除成功';
      }else{
        resObj.code = 401;
        resObj.msg = '删除失败';
      };
      res.send(resObj);
    });
  },
  getCategories(req,res){
    categoriesModel.getCategories((err,result)=>{
      if(err) console.error(err);
      let resObj = {};
       if(result){
         resObj.code = 200;
         resMsg = '获取成功';
         resObj.data = result;
       }else{
        resObj.code = 200;
        resMsg = '获取成功';
       };
       res.send(resObj);
    })
  },
  getPostsByFilter(req,res){
    // console.log(req.body);
    let {categoriesId,status,pageIndex,pageSize} = req.body;
    let offset = (pageIndex-1)*pageSize;
    let sql = `SELECT posts.id,title,posts.\`status\`,created,nickname,\`name\`
    FROM posts 
    JOIN users ON posts.user_id=users.id
    JOIN categories ON posts.category_id=categories.id   `;
    let condition = '';
    if(categoriesId != 'all' || status != 'all'){
      condition += `  WHERE `;
    }
    if(categoriesId != 'all'){
      condition += `  posts.category_id = ${categoriesId}  `
    }
    if(status != 'all'){
      if(categoriesId != 'all'){
        condition += ' AND '
      }
      condition += ` posts.\`status\`='${status}' `;
    }
    sql += condition;
    sql += `  LIMIT ${offset},${pageSize} `;
    postsModel.getPostsByFilter(sql,(err,result)=>{
      if(err) console.error(err);
      let resObj = {};
       if(result.length>0){
         resObj.code = 200;
         resMsg = '获取成功';
         resObj.data = result;
        // 获取最大页码数
        postsModel.getPostsCountAll(condition,(err,result)=>{
          if(err) console.error(err);
          if(result){
            let maxPage = Math.ceil(result[0].total / pageSize);
            resObj.maxPage = maxPage;
          }
          res.send(resObj);
        });
       }else{
        resObj.code = 200;
        resMsg = '获取成功';
        res.send(resObj);
       };
    });
  },
  uploadImage(req,res){
      //  创建一个解析post请求的对象
      let form = new formidable.IncomingForm();
      form.uploadDir = __dirname+'/../uploads'
      // 让文件保持后缀名
      form.keepExtensions = true;
      // 开始解析
      form.parse(req,(err,ziduan,wenjian)=>{
          // console.log(err);
          // console.log(ziduan);
          // console.log(wenjian);
          let resObj = {
            code : 401,
            msg : '获取失败',
          };
          if(!err){
            resObj.code = 200;
            resObj.msg = '获取成功';
            let index = wenjian.pic.path.indexOf('uploads');
            resObj.data = '/'+wenjian.pic.path.substring(index);
          }
          res.send(resObj);
      });
  },
  newPostAdd(req,res){
    let user_id = req.session.userInfo.id;
    req.body.user_id = user_id;
     postsModel.newPostAdd(req.body,(err,result)=>{
       if(err) console.error(err);
       let resObj = {
         code: 401,
         msg: '新增成功',
       };
       if(result.affectedRows == 1){
           resObj.code = 200;
           resObj.msg = '新增成功';
       };
       res.send(resObj);
     });
  },
  getPostsById(req,res){
    postsModel.getPostsById(req.query.id,(err,result)=>{
      if(err) console.error(err);
      let resObj = {
        code: 401,
        msg: '获取失败',
      };
      if(result.length > 0){
          resObj.code = 200;
          resObj.msg = '获取成功';
          resObj.data = result[0];
      };
      res.send(resObj);
    });
  },
  editPostsData(req,res){
    console.log(req.body)
    let id = req.body.id;
    delete req.body.id;
    postsModel.editPostsData(id,req.body,(err,result)=>{
      if(err) console.error(err);
      let resObj = {
        code: 401,
        msg: '编辑失败',
      }
      console.log(result);
      if(result.affectedRows == 1){
        resObj.code= 200;
        resObj.msg= '编辑成功';
      };
      res.send(resObj);
    });
  },
  newestPosts(req,res){
    postsModel.newestPosts((err,result)=>{
      if(err) console.error(err);
      let resObj = {
        code: 401,
        msg: '获取失败',
      }
      // console.log(result);
      if(result.length>0){
        resObj.code= 200;
        resObj.msg= '获取成功';
        resObj.data = result;
      };
      res.send(resObj);
    });
  },
  getcategoriPost(req,res){
    // console.log( req.query);
    let {id,pageIndex,pageSize} = req.query;
    postsModel.getcategoriPost(id,pageIndex,pageSize,(err,result)=>{
      if(err) console.error(err);
      let resObj = {
        code: 401,
        msg: '获取失败',
      }
      // console.log(result);
      if(result.length>0){
        resObj.code= 200;
        resObj.msg= '获取成功';
        resObj.data = result;
      };
      res.send(resObj);
    });
  },
  getdetailDataById(req,res){
    postsModel.getdetailDataById(req.query.id,(err,result)=>{
      if(err) console.error(err);
      let resObj = {
        code: 401,
        msg: '获取失败',
      }
      // console.log(result);
      if(result.length>0){
        resObj.code= 200;
        resObj.msg= '获取成功';
        resObj.data = result[0];
      };
      res.send(resObj);
    });
  }
};